import React, { Component, Fragment } from 'react';
import { Dispatch } from 'redux';
import { connect } from 'dva';
import router from 'umi/router';

import { Form } from '@ant-design/compatible';
import PageHeader from '@/components/PageHeader';
import { FormComponentProps } from '@ant-design/compatible/es/form';

import { Card, Button } from 'antd';

import '@ant-design/compatible/assets/index.css';
import BasicInfoElem from './components/BasicInfoElem';

interface PostChargesAddProps extends FormComponentProps {
  dispatch: Dispatch;
  dataInfo: any;
  location: { query: any };
}

@connect(({ PostChargesSaveAndEdit: { dataInfo } }: any) => ({
  dataInfo,
}))
class PostChargesAddElem extends Component<PostChargesAddProps> {
  componentDidMount() {
    const { location: { query: { id } } } = this.props;
    if (id) this.fetchDetailInfo(id);
  }

  componentDidUpdate(prevProps: any) {
    const { location: { query: { id } } } = this.props;
    if (id && prevProps.location.query.id !== id) {
      this.fetchDetailInfo(id);
    }
  }

  componentWillUnmount() {
    this.fetchAction('clear');
  }

  fetchDetailInfo = (id: number) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'PostChargesSaveAndEdit/fetch',
      payload: { id },
    });
  }

  handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();

    const { form: { validateFieldsAndScroll } } = this.props;
    validateFieldsAndScroll((errors, values) => {
      if (errors) return;

      const params = { ...values };
      const { location: { query } } = this.props;
      if (query) {
        const { id } = query;
        params.id = id;
      }
      this.fetchAction('saveOrUpdate', params);
    });
  }

  handleCancel = () => {
    router.goBack();
  }

  fetchAction = (typeName: string, payload = {}) => {
    const type = typeName.indexOf('common') >= 0 ? typeName : `PostChargesSaveAndEdit/${typeName}`;

    const { dispatch } = this.props;
    dispatch({ type, payload });
  }

  render() {
    const { form, dataInfo = {} } = this.props;

    return (
      <Fragment>
        <PageHeader />

        <Form
          hideRequiredMark
          onSubmit={this.handleSubmit}
          className="tableListForm"
        >
          <BasicInfoElem
            forms={form}
            detailInfo={dataInfo}
          />
          <Card bordered={false}>
            <Button
              type="primary"
              htmlType="submit"
            >提交
            </Button>
            <Button
              type="primary"
              ghost
              className="marginL16"
              onClick={this.handleCancel}
            >取消
            </Button>
          </Card>
        </Form>
      </Fragment>
    );
  }
}

export default Form.create<PostChargesAddProps>()(PostChargesAddElem);
